package com.seuic.hnjiningposapp.hnapps.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;


public class FtpReadFileUtils {

    /**
     * 打开FTP服务链接
     *
     * @param ftpHost     服务器地址
     * @param ftpPort     端口
     * @param ftpUserName 用户名
     * @param ftpPassword 密码
     */
    public static FTPClient getFTPClient(String ftpHost, Integer ftpPort, String ftpUserName, String ftpPassword) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.setStrictReplyParsing(false);
            ftpClient.setConnectTimeout(60000);
            if (ftpPort != null) {
                ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            } else {
                ftpClient.connect(ftpHost);// 连接FTP服务器
            }
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                if (ftpClient.login(ftpUserName, ftpPassword)) {// 登陆FTP服务器
                    if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
                            "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就使用本地编码（GBK）.
                        ftpClient.setControlEncoding("UTF-8");
                    } else {
                        ftpClient.setControlEncoding("GBK");
                    }
                    ftpClient.enterLocalPassiveMode();// 设置被动模式
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);// 设置传输的模式，以二进制流的方式读取
                    ftpClient.enterLocalPassiveMode();
                    System.out.println("FTP服务连接成功！");
                } else {
                    System.out.println("FTP服务用户名或密码错误！");
                    disConnection(ftpClient);
                }
            } else {
                System.out.println("连接到FTP服务失败！");
                disConnection(ftpClient);
            }
        } catch (SocketException e) {
            e.printStackTrace();
            disConnection(ftpClient);
            System.out.println("FTP的IP地址可能错误，请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            disConnection(ftpClient);
            System.out.println("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }

    /**
     * 关闭FTP服务链接
     */
    public static void disConnection(FTPClient ftpClient) {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件夹下的所有文件信息
     *
     * @param path 文件路径
     */
    public static FTPFile[] getFTPDirectoryFiles(FTPClient ftpClient, String path) {
        FTPFile[] files = null;
        try {
            ftpClient.changeWorkingDirectory(path);
            files = ftpClient.listFiles();
        } catch (Exception e) {
            e.printStackTrace();
            //关闭连接
            disConnection(ftpClient);
            System.out.println("FTP读取数据异常！");
        }
        return files;
    }


    /**
     * 获取文件夹下的所有文件信息
     *
     * @param path 文件路径
     */
    public static InputStream getFTPFile(FTPClient ftpClient, String path, String fileName) {
        InputStream in = null;
        try {
            ftpClient.changeWorkingDirectory(path);
            FTPFile[] files = ftpClient.listFiles();
            if (files.length > 0) {
                in = ftpClient.retrieveFileStream(fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("FTP读取数据异常！");
        } finally {
            //关闭连接
            disConnection(ftpClient);
        }
        return in;
    }


    /**
     * FTP上的文件重命名
     *
     * @param ftpClient  FTP服务链接
     * @param path       文件路径
     * @param srcName    原文件名
     * @param targetName 修改后的文件名
     * @return 修改的结果
     */
    public static boolean renameFile(FTPClient ftpClient, String path, String srcName, String targetName) {
        boolean flag = false;
        if (ftpClient != null) {
            try {
                ftpClient.changeWorkingDirectory(path);
                flag = ftpClient.rename(srcName, targetName);
            } catch (IOException e) {
                e.printStackTrace();
                disConnection(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 读取单个文件并以字符串的方式返回
     *
     * @param ftpHost     服务器IP
     * @param ftpPort     端口
     * @param ftpUserName 用户名
     * @param ftpPassword 密码
     * @param path        路径
     * @param fileName    文件名
     * @return 返回的数据
     */
    public static String FtpSingleFileData(String ftpHost, Integer ftpPort, String ftpUserName, String ftpPassword, String path, String fileName) {
        InputStream in = null;
        BufferedReader br = null;
        String data;
        StringBuilder ftpFileDataStr = new StringBuilder();
        try {
            FTPClient ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
            FTPFile[] files = getFTPDirectoryFiles(ftpClient, path);
            if (files.length==0){
                System.out.println("冠字号数据获取失败");
            }
            in = getFTPFile(ftpClient, path, fileName);
            if (in != null) {
                br = new BufferedReader(new InputStreamReader(in, "GBK"));
                while ((data = br.readLine()) != null) {
                    ftpFileDataStr.append(data);
                }
            }
            disConnection(ftpClient);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                if (br != null)
                    br.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ftpFileDataStr.toString();
    }

    /**
     * 读取多个文件并以键值对的方式返回
     *
     * @param ftpHost     服务器IP
     * @param ftpPort     端口
     * @param ftpUserName 用户名
     * @param ftpPassword 密码
     * @param path        路径
     * @return 返回的键值对
     */
    public static Map<String, String> FtpManyFileData(String ftpHost, Integer ftpPort, String ftpUserName, String ftpPassword, String path) {
        InputStream in = null;
        BufferedReader br = null;
        String data;
        Map<String, String> ftpFileDataMap = new HashMap<>();
        StringBuilder ftpFileDataStr = new StringBuilder();
        try {
            FTPClient ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
            FTPFile[] files = getFTPDirectoryFiles(ftpClient, path);
            if (files != null && files.length > 0) {
                for (FTPFile file : files) {
                    if (file.isFile()) {
                        in = ftpClient.retrieveFileStream(file.getName());
                        br = new BufferedReader(new InputStreamReader(in, "GBK"));
                        while ((data = br.readLine()) != null) {
                            ftpFileDataStr.append(data);
                        }
                        ftpFileDataMap.put(file.getName(), ftpFileDataStr.toString());
                    }
                }
            }
            disConnection(ftpClient);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ftpFileDataMap;
    }


    /**
     * 处理读取到的冠字号文件数据(维融点钞机ftp上传数据专门处理方法)
     *
     * @param data 读取到的冠字号文件数据
     * @return 处理后的数据
     */
    public static String analysisData(String data) {

        boolean flg = true;
        StringBuilder analysisDataStr = new StringBuilder();
        for (int i = 1; flg; i++) {
            int seat1 = data.indexOf("Num" + i);
            int seat2 = data.indexOf("Num" + (i + 1));
            if (seat1 != -1) {
                if (seat2 != -1) {
                    if (i < 10) {
                        analysisDataStr.append(data, seat1 + 5, seat2).append(",");
                    }
                    if (i > 9 && i < 100) {
                        analysisDataStr.append(data, seat1 + 6, seat2).append(",");
                    }
                    if (i > 99 && i < 1000) {
                        analysisDataStr.append(data, seat1 + 7, seat2).append(",");
                    }
                } else {
                    if (i < 10) {
                        analysisDataStr.append(data.substring(seat1 + 5));
                    }
                    if (i > 9 && i < 100) {
                        analysisDataStr.append(data.substring(seat1 + 6));
                    }
                    if (i > 99 && i < 1000) {
                        analysisDataStr.append(data.substring(seat1 + 7));
                    }
                }
            } else {
                flg = false;
            }
        }

        return analysisDataStr.toString();
    }

    public static void main(String[] args) {

        //FTP服务器地址
        String ftpHost = "192.168.1.200";
        //FTP端口
        Integer ftpPort = 21;
        //FTP用户名
        String ftpUserName = "ftproot";
        //FTP密码
        String ftpPassword = "netadmin";
        //文件路径
        String path = "/home/root/FSN_File/SNR/";
        //文件名
        String fileName = "SNR.ini";


        //修改文件名
//        FTPClient ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
//        System.out.println(renameFile(ftpClient, path, "SNR.ini", "SNR.pdf"));

        //读取单个
        String data = FtpSingleFileData(ftpHost, ftpPort, ftpUserName, ftpPassword, path, fileName);
        System.out.println(data);

        //处理数据
        String analysisData1 = analysisData(data);
        System.out.println(analysisData1);


        //读取多个
//        Map<String, String> map = FtpManyFileData(ftpHost, ftpPort, ftpUserName, ftpPassword, path);
//        System.out.println(map.get("SNR.ini"));


    }
}
